package com.myspring.resttest.dao.impl.continent;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.myspring.resttest.dao.continent.ContinentDaoInt;
import com.myspring.resttest.model.continent.Continent;

@EnableTransactionManagement
@Service
@Transactional
public class ContinentDaoImpl implements ContinentDaoInt {

	@Autowired
	SessionFactory	sessionFactory;

	@Override
	public void insertContinent(Continent continent) {
		sessionFactory.getCurrentSession().save(continent);
	}

	@Override
	public Continent getContinentById(int continentId) {
		return (Continent) sessionFactory.getCurrentSession().get(
				Continent.class, continentId);
	}

	@Override
	public Continent getContinent(String contName) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from Continent where name = :contname");
		query.setParameter("contname", contName);
		Continent conti = (Continent) query.list().get(0);
		Hibernate.initialize(conti.getCountries());
		return conti;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Continent> getContinents() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Continent.class);
		return criteria.list();
	}

	@Override
	public List<Continent> getContinentWithCountries() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Continent.class);
		@SuppressWarnings("unchecked")
		List<Continent> contiList = criteria.list();
		for (Continent continent : contiList) {
			Hibernate.initialize(continent.getCountries());
			//continent.getCountries();
		}
		return contiList;
	}
	
}
